'use strict';
import React from 'react';
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    DatePickerAndroid,
    TextInput,
    Platform,
    StyleSheet,
    Keyboard,
    ScrollView,
    ActivityIndicator,
    DatePickerIOS,
    Modal,
} from 'react-native';
import ToolBar from '../Components/ToolBar';
import Toast from '../Utils/toast';
import Global from '../Commom/GlobalConst';
import FoundAPIService from "../Commom/FoundAPIService";
import RuralLibraryAPIService from '../Commom/RuralLibraryAPIService';
import DateUtil from '../Commom/DateUtil';
const {width, height} = Global.Const.size;
const styles = StyleSheet.create({
  
    modalStyle: {  
    flex:1,
    alignItems: 'stretch',
    flexDirection: 'column',
    justifyContent:'flex-end',  
    backgroundColor:'rgba(200,200,200,0.3)', 
 
 },  
    DatePickerCancelView:{  
    height: height-214,    
    // backgroundColor:'rgba(25,172,26,0.3)',  
    },  
    DatePickerView:{  
        height: 214,
        backgroundColor:'#fff',         
    }, 
});

class InitiatedHelpToBuy extends React.Component {
    constructor(props) {
        super(props);
        let nowDate = new Date();
        nowDate = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1) + '-' + nowDate.getDate();
        this.state = {
            date: {startTime: nowDate, stopTime: nowDate,},
            shopList: [],
            share: [true, true],
            content: '',
            submitting: false,
            title: '',
            image: '',
            startMinimumDate:new Date(),
            stopMinimumDate:new Date(),
            showDatePickerIOS:false,
            dateType:1,
        };
    }

    async showDatePicker(timeType) {
        if (Platform.OS === 'android') {
            try {
                const {action, year, month, day} = await DatePickerAndroid.open({
                    date: new Date(),
                });
                if (action === DatePickerAndroid.dismissedAction) {
                    Toast.show('已取消选择');
                }
                if (action === DatePickerAndroid.dateSetAction) {
                    let date = this.state.date;
                    date[timeType] = year + '-' + (month + 1) + '-' + day;
                    this.setState({
                        date,
                    })
                }
            } catch ({code, message}) {
                Toast.show('操作失败')
            }
        } else {

        }

        if (Platform.OS === 'ios') {
            
            let isShow = this.state.showDatePickerIOS; 
             this.setState({  
                    showDatePickerIOS:!isShow,
                    dateType:timeType === 'startTime'?1:2  
                });  
           
           
        }
    }

    onDateChange(dateRec) {
        
        let departureDate = dateRec.getFullYear() + '-' + (dateRec.getMonth()+ 1) + '-' + dateRec.getDate();
        console.log(departureDate);

       if (this.state.dateType === 1)
       {
            let date = this.state.date;
                date['startTime'] = departureDate;
                date['stopTime'] = departureDate;
                this.setState({
                        date,
                     startMinimumDate:dateRec,
                     stopMinimumDate:dateRec,
                     })
       }else
       {
             let date = this.state.date;
                 date['stopTime'] = departureDate;
                this.setState({
                        date,
                       stopMinimumDate:dateRec,
                     })
       }
        
    }

    returnModalDatePickerView(){
        return (
             <Modal  
                                animationType='slide'  
                                transparent={true}  
                                visible={this.state.showDatePickerIOS}  
                                onShow={() => {}}  
                                onRequestClose={() => {}} > 
                             <View style={styles.modalStyle}>  
                                  <TouchableOpacity style={{}}
                                              onPress={() => this.showDatePicker(this.state.dateType)}>
                                              <View style={styles.DatePickerCancelView}> 
                                              </View> 
                                  </TouchableOpacity>
                                 <DatePickerIOS style={styles.DatePickerView}
                                    mode='date'
                                    date={this.state.dateType===1 ? this.state.startMinimumDate:this.state.stopMinimumDate}
                                    minimumDate={this.state.dateType===1 ?new Date():this.state.startMinimumDate}
                                    onDateChange={(data) => this.onDateChange(data)}
                                    />
                            </View> 
                           </Modal>
                          

        );
    }

    componentDidMount() {

        let type = this.props.type;
        if (type == 1) {
            this.setState({
                image: this.props.image,
                title: this.props.title,
            });
        } else {
            RuralLibraryAPIService.getStoreFoot(this.props.id).then((ret)=> {
                this.setState({
                    shopList: ret,
                });
            }).catch((err)=> {

            });
        }

    }

    initiated() {
        Keyboard.dismiss();
        if (!this.state.content) {
            Toast.show("请输入帮购内容");
            return;
        }
        if (Number(DateUtil.timestamp(this.state.date['startTime'])) > Number(DateUtil.timestamp(this.state.date['stopTime']))) {
            Toast.show("请选择正确的日期");
            return;
        }
        this.setState({
            submitting: true,
        });
        let type = this.props.type;
        let wanjian = [];

        if (type == 1) {
            wanjian.push(this.props.id);
        } else {
            for (let i = 0; i < this.state.shopList.length; i++) {
                wanjian.push(this.state.shopList[i].id);
            }
        }
        console.log(wanjian);
        FoundAPIService.initiatedHelpToBuy(Global.Const.token, Global.Const.registeredId, this.state.date['startTime'], this.state.date['stopTime'], this.state.content, String(wanjian)).then((ret)=> {
            this.setState({
                submitting: false,
            });
            Toast.show("发布成功");
            this.props.navigator.pop();
        }).catch((err)=> {
            this.setState({
                submitting: false,
            });
        });
    }

    onSetShare(type) {
        let share = this.state.share;
        share[type] = !share[type];
        this.setState({
            share
        })
    }

    render() {
        return (
            
            <TouchableOpacity activeOpacity={1} style={{flex: 1}} onPress={() => {
                Keyboard.dismiss();
            }}>
                <ScrollView style={{flex: 1, backgroundColor: '#F2F3F5'}}>
                    
                         { Platform.OS === 'ios' ? this.returnModalDatePickerView():null}

                    <ToolBar
                        leftFunc={()=> this.props.navigator.pop()}
                        title="发起帮购"
                        rightFunc={() => {this.initiated()}}
                        rightImage={require('../../Image/icon_green_send.png')}
                    />
                    <View style={{
                        padding: 10,
                        backgroundColor: 'white',
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginTop: 5,
                        paddingLeft: 15,
                    }}>
                        <TouchableOpacity
                            onPress={() => this.showDatePicker('startTime')}
                            style={{flex: 1}}
                        >
                            <View
                                style={{
                                    flex: 1,
                                    borderRightWidth: 1,
                                    borderRightColor: '#999',
                                }}
                            >
                                <View style={{
                                    flexDirection: 'row',
                                    alignItems: 'center'
                                }}>
                                    <Image style={{width: 15, height: 15, marginRight: 10,resizeMode: 'contain'}}
                                           source={require('../../Image/icon_gray_calendar.png')}/>
                                    <Text style={{fontSize: 14, color: '#999'}}>开始时间</Text>
                                </View>
                                <Text
                                    style={{fontSize: 14, color: Global.FontColor.DarkGray,marginTop: 10}}>{this.state.date['startTime']}</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={{flex: 1}}
                            onPress={() => this.showDatePicker('stopTime')}
                        >
                            <View style={{flex: 1, marginLeft: 10}}>
                                <View style={{
                                    flexDirection: 'row',
                                    alignItems: 'center'
                                }}>
                                    <Image style={{width: 15, height: 15, marginRight: 10,resizeMode: 'contain'}}
                                           source={require('../../Image/icon_gray_calendar.png')}/>
                                    <Text style={{fontSize: 14, color: '#999'}}>截止时间</Text>
                                </View>
                                <Text
                                    style={{fontSize: 14, color:Global.FontColor.DarkGray,marginTop: 10}}>{this.state.date['stopTime']}</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={{
                        padding: 10,
                        backgroundColor: 'white',
                        marginTop: 10,
                        paddingLeft: 15,
                        marginBottom: 1,
                    }}>
                        <View style={{
                            flexDirection: 'row',
                            alignItems: 'center',
                        }}>
                            <Image style={{width: 15, height: 15, marginRight: 10,resizeMode: 'contain'}}
                                   source={require('../../Image/icon_gray_produce.png')}/>
                            <Text style={{fontSize: 13, color: '#333'}}>产品内容</Text>
                        </View>
                        <View style={{padding: 10,flexDirection: 'row'}}>
                            {
                                this.state.shopList.length > 0 ?
                                    this.state.shopList.map((item, index)=> {
                                        return (
                                            <View key={'buy' + index} style={{width:width/3-10,alignItems: 'center'}}>
                                                <Image source={{uri:item.images}} style={{width: 80,height: 80}}/>
                                                <Text
                                                    numberOfLines={1}
                                                    style={{width: 80,textAlign: 'center',color: '#333',marginTop: 3,fontSize: 12}}>{item.title}</Text>
                                            </View>
                                        )
                                    })
                                    :
                                    <View style={{width:width/3-10,alignItems: 'center'}}>
                                        {this.state.image.length > 0 ?
                                            <Image source={{uri:this.state.image}}
                                                   style={{width: 80,height: 80}}/> : null}
                                        <Text
                                            numberOfLines={1}
                                            style={{width: 80,textAlign: 'center',color: '#333',marginTop: 3,fontSize: 12}}>{this.state.title}</Text>
                                    </View>
                            }
                        </View>
                    </View>
                    <View style={{padding: 10,backgroundColor: 'white',paddingLeft: 15,marginBottom: 10}}>
                        <View style={{flexDirection: 'row',alignItems: 'center'}}>
                            <Image style={{marginLeft:2,width: 15, height: 15, marginRight: 10,resizeMode: 'contain'}}
                                   source={require('../../Image/icon_gray_edit.png')}/>
                            <Text style={{fontSize: 13, color: '#333'}}>我想发布</Text>
                        </View>
                        <TextInput
                            textAlignVertical={'top'}
                            underlineColorAndroid={'rgba(0,0,0,0)'}
                            multiline={true}
                            placeholder={'请输入帮购内容'}
                            maxLength={100}
                            returnKeyType={'go'}
                            placeholderTextColor={'#666'}
                            value={this.state.content}
                            onChangeText={content => this.setState({ content })}
                            style={{fontSize: 13,color: '#666',lineHeight: 25,height: 80,padding: 15,flex: 1,paddingTop: 8,
                            }}
                        />
                    </View>
                </ScrollView>
                {this.state.submitting ? <View
                    style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                    <View
                        style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                        <ActivityIndicator
                            animating={this.state.animating}
                            style={{ alignItems: 'center',justifyContent: 'center'}}
                            size="large"/>
                        <Text style={{color:'white'}}>正在提交</Text>
                    </View>
                </View> : null}
            </TouchableOpacity>
        );
    }
}

export default InitiatedHelpToBuy;

// <View style={{
//                         padding: 15,
//                         flexDirection: 'row',
//                         alignItems: 'center',
//                         backgroundColor: 'white',
//                     }}>
//     <Text style={{fontSize: 12, color: '#666', marginRight: 10}}>分享到</Text>
//     <TouchableOpacity
//         onPress={() => this.onSetShare(0)}
//         style={{
//                                 borderRadius: 5,
//                                 marginRight: 10,
//                             }}
//     >
//         <Image style={{width: 40,height: 40}}
//                source={this.state.share[0] ? require('../../Image/icon_share_01.png')
//                                        : require('../../Image/un_icon_share_01.png')}/>
//     </TouchableOpacity>
//     <TouchableOpacity
//         onPress={() => this.onSetShare(1)}
//         style={{
//                                 borderRadius: 5,
//                                 marginRight: 10,
//                             }}
//     >
//         <Image style={{width: 40,height: 40}}
//                source={this.state.share[1] ? require('../../Image/icon_share_02.png')
//                                        : require('../../Image/un_icon_share_02.png')}/>
//     </TouchableOpacity>
// </View>